from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin
from rest_framework.exceptions import APIException
from apps.models import HouseKeeping, Tag, User
from apps.serializers.ListHousekeeping import ListThingSerializer
from apps.utils.common_function import log_error
from apps.utils.common_mixin import APIListModelMixin,APICreateModelMixin
from apps.utils.common_response import APIResponse

from rest_framework.decorators import action
from rest_framework import status


class HouseKeepingView(GenericViewSet):
    authentication_classes = []
    permission_classes = []
    # 查询
    def list(self, request):
        keyword = request.GET.get("keyword", None)
        # 分类
        c = request.GET.get("c", None)
        tag = request.GET.get("tag", None)
        sort = request.GET.get("sort", 'recent')
        # 排序方式
        order = '-create_time'
        if sort == 'recent':
            order = '-create_time'
        # 热门和推荐的
        elif sort == 'hot' or sort == 'recommend':
            # pv访问量
            order = '-pv'

        if keyword:
            # 标题中包含指定关键词的所有记录都会被选中,按更新时间倒序排序
            things = HouseKeeping.objects.filter(title__contains=keyword).filter(status='0').order_by(order)
        # 如果有c且是有效分类ID，按分类ID过滤
        elif c and int(c) > -1:
            # 包含一个或多个ID的列表
            ids = [c]
            things = HouseKeeping.objects.filter(classification_id__in=ids).filter(status='0').order_by(order)
        elif tag:
            tag = Tag.objects.get(id=tag)
            print(tag)
            # 反向关联
            things = tag.thing_set.all().filter(status='0').order_by(order)
        else:
            # 不加载wish字段
            things = HouseKeeping.objects.all().filter(status='0').order_by(order)
        serializer = ListThingSerializer(things, many=True)
        return APIResponse(msg='查询成功', data=serializer.data)


class PV(GenericViewSet):
    authentication_classes = []
    permission_classes = []
    def list(self, request, *args, **kwargs):
        try:
            # 从最后向上看id
            pk = request.GET.get('id', -1)
            thing = HouseKeeping.objects.get(pk=pk)
            # 访客量加一
            thing.pv = thing.pv + 1
            thing.save()
        except HouseKeeping.DoesNotExist:
            # 错误日志
            log_error(request, '对象不存在')
            return APIResponse(code=1, msg='对象不存在')
        serializer = ListThingSerializer(thing)
        return APIResponse(msg='查询成功', data=serializer.data)




class IncreaseCollect(GenericViewSet):

    queryset = HouseKeeping.objects.all()

    def create(self, request):
        try:
            username = request.GET.get('username', None)
            thingId = request.GET.get('thingId', None)

            if username and thingId:
                #User模型的实例
                user = User.objects.get(username=username)
                thing = HouseKeeping.objects.get(pk=thingId)
                # print(thing.collect_count,type(thing.collect_count))
                if thing.collect_count>=1:
                    return APIResponse(msg='已经加入过收藏啦~')
                if user not in thing.collect.all():
                    # print(thing.collect.all())
                    thing.collect.add(user)
                    thing.collect_count += 1
                    print(thing.collect_count)
                    thing.save()
            serializer = ListThingSerializer()
            return APIResponse(code=0, msg='收藏成功~', data=serializer.data)
        except HouseKeeping.DoesNotExist:
            log_error(request, '操作失败')
            return APIResponse(code=1, msg='操作失败')


class GetCollectThingListView(GenericViewSet):
    def list(self, request):
        try:
            # 前端需要拿到用户名
            username = request.GET.get('username')
            # 如果有当前用户名的话
            if username:
                user = User.objects.get(username=username)
                # 反向关联
                thing = user.collect_things.all()
                serializer = ListThingSerializer(thing, many=True)
                return APIResponse(msg='该用户收藏数据', data=serializer.data)
            else:
                return APIResponse(code=1, msg='用户名不存在')
        except Exception as e:
            log_error(request, '操作失败' + str(e))
            return APIResponse(code=1, msg='获取收藏失败')
        
        
        
# class removeCollectUser(GenericViewSet,APICreateModelMixin):
#     queryset=  HouseKeeping.objects.all()
#     serializer_class=CollectSerializer  


# 移除收藏
# http://127.0.0.1:8000/api/v1/removeCollectUser/
class removeCollectUser(GenericViewSet):
    def create(self, request):
        try:
            username = request.GET.get('username', None)
            thingId = request.GET.get('thingId', None)
            if username and thingId:
                user = User.objects.get(username=username)
                thing = HouseKeeping.objects.get(pk=thingId)
                # 看用户名在不在里面
                if user in thing.collect.all():
                    thing.collect.remove(user)
                    thing.collect_count -= 1
                    thing.save()
        except HouseKeeping.DoesNotExist:
            log_error(request, '操作失败')
            return APIResponse(code=1, msg='操作失败')
        return APIResponse(code=0, msg='操作成功')

class ListUserCenterThing(GenericViewSet):
    def list(self,request):
        user = request.GET.get("user", None)
        if user:
            things = HouseKeeping.objects.filter(user=user)
            serializer = ListThingSerializer(things, many=True)
            return APIResponse(code=0, msg='查询成功', data=serializer.data)
        else:
            return APIResponse(code=1, msg='user不能为空')